package com.xxxx.manager.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxxx.common.result.BaseResult;
import com.xxxx.common.utils.JsonUtil;
import com.xxxx.manager.mapper.GoodsMapper;
import com.xxxx.manager.pojo.Goods;
import com.xxxx.manager.pojo.GoodsExample;
import com.xxxx.manager.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.HtmlUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author Str
 * @Date 2021/10/5 20:53
 * @Description :商品服务实现类
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 商品新增-保存
     *
     * @param goods
     * @return
     */
    @Override
    public BaseResult saveGoods(Goods goods) {
        // 如果已经保存成功，则返回前端页面错误信息
        // 这是为了让点击留在本页的时候，再次点击保存则不会保存成功
        if (null != goods.getGoodsId()) {
            return BaseResult.error();
        }
        // 清空redis
        redisTemplate.delete(redisTemplate.keys("goods*"));
        // 设置富文本编辑器转义，因为富文本编辑器本质上是一个html页面
        if (!StringUtils.isEmpty(goods.getGoodsContent())) {
            goods.setGoodsContent(HtmlUtils.htmlEscape(goods.getGoodsContent(), "UTF-8"));
        }
        // 保存
        int result = goodsMapper.insertSelective(goods);
        // 判断保存结果
        BaseResult baseResult = BaseResult.error();
        if (0 < result) {
            baseResult = BaseResult.success();
            // 保存成功存入商品id，返回到前端
            baseResult.setMessage(String.valueOf(goods.getGoodsId()));
        } else {
            baseResult = BaseResult.error();
        }
        return baseResult;
    }

    /**
     * 商品-列表-分页查询
     *
     * @param goods
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public BaseResult selectGoodsListByPage(Goods goods, Integer pageNum, Integer pageSize) {
        /**
         * 商品列表RedisKey
         *  1.无条件查询
         *      goods:pageNum_:PageSize_:catId_:brandId_:goodsName_:
         *  2.条件查询
         *      goods:pageNum_:PageSize_:catId_123:brandId_:goodsName_:
         *      goods:pageNum_:PageSize_:catId_:brandId_123:goodsName_:
         *      goods:pageNum_:PageSize_:catId_:brandId_:goodsName_华为:
         *      goods:pageNum_:PageSize_:catId_123:brandId_123:goodsName_:
         *      goods:pageNum_:PageSize_:catId_123:brandId_:goodsName_华为:
         *      goods:pageNum_:PageSize_:catId_:brandId_123:goodsName_华为:
         *      goods:pageNum_:PageSize_:catId_123:brandId_123:goodsName_华为:
         */
        //定义RedisKey数组
        String[] goodsKeyArr = new String[]{
                "goods:pageNum_" + pageNum + ":PageSize_" + pageSize + ":",
                "catId_:",
                "brandId_:",
                "goodsName_:"
        };
        //构建分页对象
        PageHelper.startPage(pageNum, pageSize);
        //创建查询对象
        GoodsExample example = new GoodsExample();
        GoodsExample.Criteria criteria = example.createCriteria();
        //设置查询条件
        //分类参数
        if (null != goods.getCatId() && 0 != goods.getCatId()) {
            criteria.andCatIdEqualTo(goods.getCatId());
            goodsKeyArr[1] = "catId_" + goods.getCatId() + ":";
        }
        //品牌参数
        if (null != goods.getBrandId() && 0 != goods.getBrandId()) {
            criteria.andBrandIdEqualTo(goods.getBrandId());
            goodsKeyArr[2] = "brandId_" + goods.getBrandId() + ":";
        }
        //关键词
        if (!StringUtils.isEmpty(goods.getGoodsName())) {
            criteria.andGoodsNameLike("%" + goods.getGoodsName() + "%");
            goodsKeyArr[3] = "goodsName_" + goods.getGoodsName() + ":";
        }
        //拼接完整的RedisKey
        String goodsListKey = Arrays.stream(goodsKeyArr).collect(Collectors.joining());
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        //查询缓存，如果缓存中存在数据，直接返回
        String pageInfoGoodsJson = valueOperations.get(goodsListKey);
        if (!StringUtils.isEmpty(pageInfoGoodsJson)) {
            return BaseResult.success(JsonUtil.jsonStr2Object(pageInfoGoodsJson, PageInfo.class));
        }

        //==============错误代码==================
        // String listGoodsJson = valueOperations.get(goodsListKey);
        // if (!StringUtils.isEmpty(listGoodsJson)){
        // 	List<Goods> goodsList = JsonUtil.jsonToList(listGoodsJson, Goods.class);
        // 	PageInfo<Goods> pageInfo = new PageInfo<>(goodsList);
        // 	return BaseResult.success(pageInfo);
        // }
        //==============错误代码==================

        //判断查询结果是否为空，不为空放入分页对象
        List<Goods> list = goodsMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            PageInfo<Goods> pageInfo = new PageInfo<>(list);
            //放入缓存
            // 放入PageInfo对象不放Goods对象是因为PageInfo是PageHelper的插件，PageHelper只有拿到从数据库查到的数据分页才能生效
            // 而商品信息第一次查是从数据库查的，之后就是从redis中查，所以之后只能看到第一次查的数据而不能看到别的数据
            valueOperations.set(goodsListKey, JsonUtil.object2JsonStr(pageInfo));
            //==============错误代码==================
            // valueOperations.set(goodsListKey,JsonUtil.object2JsonStr(list));
            //==============错误代码==================
            return BaseResult.success(pageInfo);
        } else {
            //如果没有数据，将空数据放入缓存，设置失效时间60s
            valueOperations.set(goodsListKey, JsonUtil.object2JsonStr(new PageInfo<>(new ArrayList<Goods>())), 60, TimeUnit.SECONDS);
        }
        return BaseResult.error();
    }
}
